package com.apexwear.apexutils.data;

import android.app.Activity;
import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.apex.bluetooth.callback.WatchInfoCallback;
import com.apex.bluetooth.core.EABleManager;
import com.apex.bluetooth.enumeration.QueryWatchInfoType;
import com.apex.bluetooth.model.EABleWatchInfo;
import com.apexwear.apexutils.model.Ota;
import com.apexwear.apexutils.utils.FileUtils;

import net.lingala.zip4j.ZipFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;


public class OtaData extends AndroidViewModel {
    Thread mThread;
    MutableLiveData<List<Ota>> mutableLiveData = new MutableLiveData<>();
    public MutableLiveData<Ota> otaData = new MutableLiveData<>();
    public MutableLiveData<Boolean> watchLive = new MutableLiveData<>();
    final String TAG = this.getClass().getSimpleName();
    List<String> fileList;

    public OtaData(@NonNull Application application) {
        super(application);
    }

    public MutableLiveData<List<Ota>> getData() {

        mThread = new Thread() {
            @Override
            public void run() {
                super.run();
                List<Ota> otaList = FileUtils.getOtaFile(getApplication());
                if (otaList != null && !otaList.isEmpty()) {
                    mutableLiveData.postValue(otaList);
                } else {
                    mutableLiveData.postValue(null);
                }
            }
        };
        mThread.start();
        return mutableLiveData;
    }

    public MutableLiveData<Boolean> saveFile(String srcFile, String newFileName) {
        MutableLiveData<Boolean> mutableLiveData = new MutableLiveData<>();
        if (TextUtils.isEmpty(srcFile) || TextUtils.isEmpty(newFileName)) {
            mutableLiveData.postValue(false);
        } else {
            File f = new File(srcFile);
            if (!f.exists() || f.isDirectory()) {
                mutableLiveData.postValue(false);
            } else {
                mThread = new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        boolean success = FileUtils.saveFile(newFileName, getApplication(), srcFile);
                        mutableLiveData.postValue(success);
                    }
                };
                mThread.start();
            }
        }
        return mutableLiveData;
    }

    public void getCurrentOtaInfo(final Ota ota) {
        if (mThread != null) {
            mThread.interrupt();
            mThread = null;
        }
        mThread = new Thread() {
            @Override
            public void run() {
                super.run();
                ZipFile zFile = new ZipFile(ota.getFilePath());
                // 尝试读取一个条目，如果能成功读取，则说明文件是ZIP格式
                if (zFile != null && zFile.isValidZipFile()) {
                    File file = new File(ota.getFilePath());
                    final String outPath = file.getParent() + "/his";
                    int result = unZip(ota.getFilePath(), outPath);
                    if (result != 0) {
                        otaData.postValue(null);
                    } else {
                        String jsonFile = getGsonFile(outPath);
                        if (TextUtils.isEmpty(jsonFile)) {
                            if (otaData != null) {
                                otaData.postValue(null);
                            }
                            return;
                        }
                        Ota zipOta = new Ota();
                        zipOta.setWatchName(ota.getWatchName());
                        zipOta.setOtaVersion(ota.getOtaVersion());
                        zipOta.setFileName(new File(jsonFile).getName());
                        zipOta.setFilePath(jsonFile);
                        zipOta.setFileType("his_json");
                        if (otaData != null) {
                            otaData.postValue(zipOta);
                        }
                        return;

                    }
                } else {
                    if (otaData != null) {
                        otaData.postValue(ota);
                    }
                    return;
                }


                if (otaData != null) {
                    otaData.postValue(null);
                }


            }
        };
        mThread.start();


    }

    private int unZip(final String oriFile, final String unZipFile) {

        try {

            File file = new File(unZipFile);
            if (file != null && file.exists()) {
                fileList = new ArrayList<>();
                getAllFilePath(file.getPath());
                if (fileList != null && !fileList.isEmpty()) {
                    for (int i = 0; i < fileList.size(); i++) {
                        File f = new File(fileList.get(i));
                        f.delete();
                    }
                }
            }
            ZipFile zFile = new ZipFile(oriFile);
            File destDir = new File(unZipFile);     // 解压目录
            if (destDir.isDirectory() && !destDir.exists()) {
                destDir.mkdir();
            }
            zFile.extractAll(unZipFile);
            return 0;
        } catch (Exception e) {
            Log.e(TAG, "错误:" + e.getMessage());
            return -1;
        }
    }

    private String getGsonFile(final String outPath) {
        if (fileList == null) {
            fileList = new ArrayList<>();
        }
        fileList.clear();
        getAllFilePath(outPath);
        if (fileList == null || fileList.isEmpty()) {
            return null;
        }
        for (String fileName : fileList) {
            if (!TextUtils.isEmpty(fileName)) {
                File f = new File(fileName);
                if (f != null && f.exists() && f.isFile()) {
                    String[] nameArray = fileName.split("\\.");
                    if ("json".equalsIgnoreCase(nameArray[nameArray.length - 1])) {
                        return fileName;
                    }
                }
            }
        }
        return null;
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (mThread != null) {
            mThread.interrupt();
            mThread = null;
        }
    }

    public void is707() {
        EABleManager.getInstance().queryWatchInfo(QueryWatchInfoType.watch_info, new WatchInfoCallback() {
            @Override
            public void watchInfo(EABleWatchInfo eaBleWatchInfo) {
                if (eaBleWatchInfo != null) {
                    if (eaBleWatchInfo.getLcd_pixel_type() == 4 || eaBleWatchInfo.getLcd_pixel_type() == 5) {
                        if (watchLive != null) {
                            watchLive.postValue(true);
                        }
                        return;
                    }
                }
                if (watchLive != null) {
                    watchLive.postValue(false);
                }
            }

            @Override
            public void mutualFail(int i) {
                if (watchLive != null) {
                    watchLive.postValue(false);
                }
            }
        });
    }

    private void getAllFilePath(final String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (file.isFile()) {
            if (fileList != null) {
                fileList.add(file.getPath());
            }
            return;
        }

        File[] fList = file.listFiles();
        if (fList == null) {
            if (fileList != null) {
                fileList.add(file.getPath());
            }
            return;
        }
        for (int i = 0; i < fList.length; i++) {
            File f = fList[i];
            if (f != null && f.exists()) {
                getAllFilePath(f.getPath());
            }
        }
        if (fileList != null) {
            fileList.add(file.getPath());
        }

    }

}
